package vashion.azeroth.core.oss;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.ObjectMetadata;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;

/**
 * 图片处理工具类
 * Created by xiaonan on 15/9/6.
 */
public class OSSImageProcessUtil {

    private static final Logger logger = LoggerFactory.getLogger(OSSImageProcessUtil.class);
    private static final String UPLOAD_ITEM_FILE_FOLDER = "vashion-item";
    private static final String UPLOAD_ARTICLE_FILE_FOLDER = "vashion-article";
    public static final String OSSCONFIG_PATH = "ossconfig.properties";
    public static final String imagePath = "itemimg";

    private static OSSClient instance;
    private static OSSConfigure ossConfigure;

    private static OSSClient getInstance() throws Exception {
        if (instance == null) {
            synchronized (OSSImageProcessUtil.class) {
                if (instance == null) {
                    ossConfigure = new OSSConfigure(OSSCONFIG_PATH);
                    instance = ossConfigure.getOssClient();
                }
            }
        }
        return instance;

    }

    /**
     * 上传宝贝图片使用此方法
     *
     * @param inputStream
     * @param remotePath
     * @return
     * @throws Exception
     */
    public static String uploadItemFile(InputStream inputStream, String contentType, String fileName, String remotePath) throws Exception {
        //为了防止图片名重复，加上随机字串前缀

        fileName = vashion.azeroth.core.StringUtils.generateShortUuid() + "_" + fileName;
        return uploadStream(inputStream, contentType, fileName, remotePath, UPLOAD_ITEM_FILE_FOLDER);
    }

    public static List<String> getFileList(String prefix) {
        try {
            OSSClient ossClient = getInstance();
            ObjectListing objectListing = ossClient.listObjects(ossConfigure.getBucketName(), prefix);
            List<OSSObjectSummary> objectSummaries = objectListing.getObjectSummaries();
            List<String> resultList = Lists.newArrayList();
            for (OSSObjectSummary ossObjectSummary : objectSummaries) {
                resultList.add(ossObjectSummary.getKey());
            }
            return resultList;
        } catch (Throwable e) {
            logger.error("getItemFileList exception", e);
            return Lists.newArrayList();
        }
    }

    /**
     * 上传文章图片使用此方法
     *
     * @param file
     * @param remotePath
     * @return
     * @throws Exception
     */
    public static String uploadArticleFile(File file, String remotePath) throws Exception {
        return uploadFile(file, remotePath, UPLOAD_ARTICLE_FILE_FOLDER);
    }

    /**
     * 上传OSS服务器文件
     *
     * @param @param  ossConfigure
     * @param @param  file
     * @param @param  remotePath
     * @param @return
     * @param @throws Exception    设定文件
     * @return String    返回类型
     * @throws
     * @Title: uploadFile
     * @Description:
     */
    public static String uploadFile(File file, String remotePath, String folder) throws Exception {

        if (file == null) {
            logger.error("uploadFile file is null");
            return "";
        }
        try {
            InputStream fileContent = new FileInputStream(file);
            OSSClient ossClient = getInstance();
            String remoteFilePath = remotePath.substring(0, remotePath.length()).replaceAll("\\\\", "/") + "/";
            //创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(fileContent.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            objectMetadata.setContentType(contentType(file.getName().substring(file.getName().lastIndexOf("."))));
            // 获得文件后缀名称
            String suffixName = file.getName().substring(file.getName().lastIndexOf("."));
            String fileName = System.currentTimeMillis() + suffixName;
            objectMetadata.setContentDisposition("inline;filename=" + fileName);
            //上传文件
            if (StringUtils.isBlank(folder)) {
                folder = ossConfigure.getBucketName();
            }
            ossClient.putObject(folder, remoteFilePath + fileName, fileContent, objectMetadata);
//            logger.error("uploadFile path:{}", ossConfigure.getAccessUrl() + "/" + remoteFilePath + file.getName());
            logger.error("uploadFile path:{}", remoteFilePath + file.getName());
            return remoteFilePath + fileName;
        } catch (Exception e) {
            logger.error("uploadFile exception,fileName=" + file.getName(), e);
            return "";
        }
    }

    /**
     * 上传OSS服务器stream
     *
     * @param @param  ossConfigure
     * @param @param  inputStream
     * @param @param  remotePath
     * @param @return
     * @param @throws Exception    设定文件
     * @return String    返回类型
     * @throws
     * @Title: uploadFile
     * @Description:
     */
    public static String uploadStream(InputStream inputStream, String contentType, String fileName, String remotePath, String folder) throws Exception {

        try {
            OSSClient ossClient = getInstance();
            String remoteFilePath = remotePath.substring(0, remotePath.length()).replaceAll("\\\\", "/") + "/";
            //创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(inputStream.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            objectMetadata.setContentType(contentType);
            // 获得文件后缀名称,不能设置这个数据，设置了就直接下载了
//            objectMetadata.setContentDisposition("inline;filename=" + fileName);
            //上传文件
            if (StringUtils.isBlank(folder)) {
                folder = ossConfigure.getBucketName();
            }
            ossClient.putObject(folder, remoteFilePath + fileName, inputStream, objectMetadata);
            logger.error("uploadFile path:{}", ossConfigure.getAccessUrl() + "/" + remoteFilePath + fileName);
            return ossConfigure.getAccessUrl() + "/" + remoteFilePath + fileName;
        } catch (Exception e) {
            logger.error("uploadFile exception,fileName=" + fileName, e);
            return "";
        }
    }

    /**
     * 根据key删除OSS服务器上的文件
     *
     * @param @param ossConfigure
     * @param @param filePath    设定文件
     * @return void    返回类型
     * @throws
     * @Title: deleteFile
     * @Description:
     */
    public static void deleteFile(String filePath) {
        try {

            OSSClient ossClient = getInstance();
            ossClient.deleteObject(ossConfigure.getBucketName(), filePath);
        } catch (Exception e) {
            logger.error("deleteFile exception,filePath=" + filePath, e);
        }

    }

    /**
     * Description: 判断OSS服务文件上传时文件的contentType
     *
     * @param FilenameExtension 文件后缀
     * @return String
     * @Version1.0
     */
    public static String contentType(String FilenameExtension) {
        if (FilenameExtension.equals("BMP") || FilenameExtension.equals("bmp")) {
            return "image/bmp";
        }
        if (FilenameExtension.equals("GIF") || FilenameExtension.equals("gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equals("JPEG") || FilenameExtension.equals("jpeg") ||
                FilenameExtension.equals("JPG") || FilenameExtension.equals("jpg") ||
                FilenameExtension.equals("PNG") || FilenameExtension.equals("png")) {
            return "image/jpeg";
        }
        if (FilenameExtension.equals("HTML") || FilenameExtension.equals("html")) {
            return "text/html";
        }
        if (FilenameExtension.equals("TXT") || FilenameExtension.equals("txt")) {
            return "text/plain";
        }
        if (FilenameExtension.equals("VSD") || FilenameExtension.equals("vsd")) {
            return "application/vnd.visio";
        }
        if (FilenameExtension.equals("PPTX") || FilenameExtension.equals("pptx") ||
                FilenameExtension.equals("PPT") || FilenameExtension.equals("ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (FilenameExtension.equals("DOCX") || FilenameExtension.equals("docx") ||
                FilenameExtension.equals("DOC") || FilenameExtension.equals("doc")) {
            return "application/msword";
        }
        if (FilenameExtension.equals("XML") || FilenameExtension.equals("xml")) {
            return "text/xml";
        }
        return "text/html";
    }

    public static void main(String[] args) {
        try {
//			File file = new File("/Users/koudai235/Downloads/mrwhiteegg.png");
//			String result = uploadFile(file,"abcd1234",UPLOAD_ITEM_FILE_FOLDER);
//			System.out.println(result);
            getFileList("");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
